package cn.com.lyj6851.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import cn.com.lyj6851.common.properties.SecurityConstants;
import cn.com.lyj6851.common.util.ResultUtil;
import cn.com.lyj6851.common.properties.LoginResponseType;
import cn.com.lyj6851.common.properties.RootSecurityProperties;
import lombok.extern.slf4j.Slf4j;

/**
 * 处理需要身份认证的请求
 */

@RestController
@Slf4j
public class BrowserSecurityController {
	
    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    
    @Autowired
    private RootSecurityProperties securityProperties;

    /**
     * 当需要身份认证时，跳转到这里 "/authentication/require"
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public Object requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {

        SavedRequest savedRequest = requestCache.getRequest(request, response);
                
        if(savedRequest != null && LoginResponseType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
        	log.info("引发跳转的请求是:"+savedRequest);
        	return ResultUtil.error(HttpStatus.UNAUTHORIZED.value(), "访问的服务需要身份认证，请引导用户到登录页");
        }else {
        	redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
        }
        return ResultUtil.error(HttpStatus.UNAUTHORIZED.value(), "访问的服务需要身份认证，请引导用户到登录页");
    }
}
